import os
import logging
import time
from logging.handlers import TimedRotatingFileHandler
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
log_path = os.path.join(parent_dir, 'logs')


# 禁用 paddlex 包的日志输出
logging.getLogger('paddlex').setLevel(logging.CRITICAL)

def setup_logging(
    log_path= log_path,
    log_level=logging.INFO,
    backup_count=30
):
    """
    高级日志初始化：支持控制台+文件，自动去重，日期文件夹管理
    Args:
        log_path (str): 日志根目录
        log_level (int): 日志级别
        backup_count (int): 文件日志最多保留数量
    """
    logger = logging.getLogger()
    # ====== 1. 清空历史 handler 防止重复输出 ======
    if logger.hasHandlers():
        logger.handlers.clear()

    # ====== 2. 构建日志目录、文件名 ======
    date_str = time.strftime('%Y-%m-%d')
    folder = os.path.join(log_path, date_str)
    os.makedirs(folder, exist_ok=True)
    time_str = time.strftime('%H-%M-%S')
    log_file = os.path.join(folder, f'{time_str}.log')

    # ====== 3. 定义日志格式 ======
    formatter = logging.Formatter(
        '[%(asctime)s] [%(levelname)8s] %(filename)s:%(lineno)d - %(message)s'
    )

    # ====== 4. 文件日志，支持自动轮转 ======
    file_handler = TimedRotatingFileHandler(
        log_file,
        when='midnight',
        interval=1,
        backupCount=backup_count,
        encoding='utf-8'
    )
    file_handler.setLevel(log_level)
    file_handler.setFormatter(formatter)

    # ====== 5. 控制台日志 ======
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(log_level)
    stream_handler.setFormatter(formatter)

    # ====== 6. 添加 handler 到 root logger ======
    logger.setLevel(log_level)
    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)

    # ====== 7. 可选：打印当前handlers，验证无重复 ======
    # print("当前handler:", logger.handlers)

# ====== 用法举例 ======
if __name__ == '__main__':
    setup_logging()
    logging.info("至尊大人，您的日志系统已就绪，无分身，无重复！")
